package com.vicene.gmail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.vicene.gmail.common.utils.HttpUtil;
import com.vicene.gmail.member.dao.MemberLevelDao;
import com.vicene.gmail.member.entity.MemberLevelEntity;
import com.vicene.gmail.member.exception.PhoneExistException;
import com.vicene.gmail.member.exception.UsernameExistException;
import com.vicene.gmail.member.vo.MemberLoginVo;
import com.vicene.gmail.member.vo.MemberRegistVo;
import com.vicene.gmail.member.vo.WeiBoAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vicene.gmail.common.utils.PageUtils;
import com.vicene.gmail.common.utils.Query;

import com.vicene.gmail.member.dao.MemberDao;
import com.vicene.gmail.member.entity.MemberEntity;
import com.vicene.gmail.member.service.MemberService;
import org.thymeleaf.util.StringUtils;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();

        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        checkPhoneUnique( vo.getPhone());
        checkUsernameUnique( vo.getUserName());


        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao =this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile" , phone));
        if(count > 0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException {
        MemberDao memberDao =this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username" , userName));
        if(count > 0){
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username" , vo.getLoginacct()).
                or().eq("mobile" , vo.getLoginacct()));

        if(memberEntity == null){
            return null;
        }else {
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches =  passwordEncoder.matches(vo.getPassword() , passwordDb);
            if(matches){
                return memberEntity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(WeiBoAuth vo) {
        String uid = vo.getUid();

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid" , uid));

        if(memberEntity != null){
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in());
            this.baseMapper.updateById(update);
            memberEntity.setAccessToken(vo.getAccess_token());
            return memberEntity;
        }else{
            MemberEntity insert = new MemberEntity();

            Map<String ,String> params = new HashMap();
            params.put("access_token"  , vo.getAccess_token());
            params.put("uid"  , vo.getUid());

            String json = HttpUtil.doGet("https://api.weibo.com/2/users/show.json" , params);
            if(!StringUtils.isEmpty(json)){
                JSONObject jsonObject = JSON.parseObject(json);
                insert.setNickname(jsonObject.getString("name"));
                insert.setGender("m".equals(jsonObject.getString("gender"))?1:0);
            }

            insert.setSocialUid(vo.getUid());
            insert.setAccessToken(vo.getAccess_token());
            insert.setExpiresIn(vo.getExpires_in());
            this.baseMapper.insert(insert);
            return insert;
        }

    }


}